home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9597 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: news.mira.net.au!news
  2. From: davidw@werple.net.au (David White)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: polymorphism and style
  5. Date: 3 Mar 1996 12:18:30 +1100
  6. Organization: Werple Internet, Melbourne
  7. Message-ID: <4has16$cge@werple.net.au>
  8. References: <4gr4ur$n13@alpha.pcix.com> <DnI6II.KMt@news.arco.com> <4h4h3h$6ur@brtph500.bnr.ca>
  9. NNTP-Posting-Host: werple.mira.net.au
  10.  
  11. oophelp@bnr.ca (OOP Helpline) writes:
  12.  
  13.  
  14. >|> >  Question on polymorphism and style.
  15. >|> >Want to call a function in a most derived class off a pointer to the base
  16. >|> >class. The fuction does not exist in the base class.
  17. >|> >I should:
  18. >|> >1)downcast ?
  19. >|> >2)add the function to the base class and add virtual stubs to every 
  20. >|> >  class that does not use it ? 
  21. >|> >3)add it to the base class but define it like 
  22. >|> >     foo( ..whatever..) {error_msg("virtual function not defined");}
  23. >|> >  This way only the class that uses it would have to define it.
  24. >|> >4) ?
  25. >|> > 
  26. >|> >thanks for your time.
  27.  
  28. >|>but maybe you need to take another
  29. >|> look at your design.
  30.  
  31. >Exactly, this is clearly a design fault. Upcasting a derived class object
  32. >to a base class requires that you only do base class operations on it.
  33. >(While any pilot can be a passenger on an airplane, any passenger cannot
  34. >be a pilot.)
  35.  
  36. >If you need to keep the ability to do derived class behavior on a derived
  37. >class object, you need to keep a derived class reference to it
  38. >(i.e. use two pointers to the derived class object, one for use
  39. >for base class behavior and one for use for derived class behavior).
  40.  
  41. There are many occasions when this is not practical. Suppose I have an
  42. array of base class object pointers; at some stage I might want to iterate
  43. over them, retrieve the derived classes, and call functions specific to the
  44. derived type. Or I might pass an object pointer to something and receive
  45. it back later and have to retrieve the derived class. These are exactly
  46. the kinds of situations that 'dynamic_cast' was intended for. Your
  47. suggestion can unnecessarily complicate the design, rather than simplify
  48. it. To state, without qualification, that "this is clearly a design fault"
  49. demonstrates ignorance of real situations in OO design. And this from an
  50. OO helpline! 
  51.  
  52. David White
  53. davidw@werple.mira.net.au
  54.  
  55.